<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wrr123.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="闲时与你立黄昏，笑问灶前粥可温。">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ Tutorials">
<meta property="og:url" content="https://wrr123.github.io/2021/12/22/RabbitMQ-Tutorials/index.html">
<meta property="og:site_name" content="一缕烟气">
<meta property="og:description" content="闲时与你立黄昏，笑问灶前粥可温。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/001.png">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/002.png">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/003.png">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/004.png">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/005.png">
<meta property="og:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/006.png">
<meta property="article:published_time" content="2021-12-22T09:42:42.000Z">
<meta property="article:modified_time" content="2022-02-18T02:52:04.358Z">
<meta property="article:author" content="田园隐士">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/001.png">

<link rel="canonical" href="https://wrr123.github.io/2021/12/22/RabbitMQ-Tutorials/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>RabbitMQ Tutorials | 一缕烟气</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<style>mjx-container[jax="SVG"] {
  direction: ltr;
}

mjx-container[jax="SVG"] > svg {
  overflow: visible;
}

mjx-container[jax="SVG"][display="true"] {
  display: block;
  text-align: center;
  margin: 1em 0;
}

mjx-container[jax="SVG"][justify="left"] {
  text-align: left;
}

mjx-container[jax="SVG"][justify="right"] {
  text-align: right;
}

g[data-mml-node="merror"] > g {
  fill: red;
  stroke: red;
}

g[data-mml-node="merror"] > rect[data-background] {
  fill: yellow;
  stroke: none;
}

g[data-mml-node="mtable"] > line[data-line] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > rect[data-frame] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > .mjx-dashed {
  stroke-dasharray: 140;
}

g[data-mml-node="mtable"] > .mjx-dotted {
  stroke-linecap: round;
  stroke-dasharray: 0,140;
}

g[data-mml-node="mtable"] > svg {
  overflow: visible;
}

[jax="SVG"] mjx-tool {
  display: inline-block;
  position: relative;
  width: 0;
  height: 0;
}

[jax="SVG"] mjx-tool > mjx-tip {
  position: absolute;
  top: 0;
  left: 0;
}

mjx-tool > mjx-tip {
  display: inline-block;
  padding: .2em;
  border: 1px solid #888;
  font-size: 70%;
  background-color: #F8F8F8;
  color: black;
  box-shadow: 2px 2px 5px #AAAAAA;
}

g[data-mml-node="maction"][data-toggle] {
  cursor: pointer;
}

mjx-status {
  display: block;
  position: fixed;
  left: 1em;
  bottom: 1em;
  min-width: 25%;
  padding: .2em .4em;
  border: 1px solid #888;
  font-size: 90%;
  background-color: #F8F8F8;
  color: black;
}

foreignObject[data-mjx-xml] {
  font-family: initial;
  line-height: normal;
  overflow: visible;
}

.MathJax path {
  stroke-width: 3;
}

mjx-container[display="true"] {
  overflow: auto hidden;
}

mjx-container[display="true"] + br {
  display: none;
}
</style><link rel="alternate" href="/atom.xml" title="一缕烟气" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一缕烟气</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">沧海月明珠有泪，蓝田日暖玉生烟</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wrr123.github.io/2021/12/22/RabbitMQ-Tutorials/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="田园隐士">
      <meta itemprop="description" content="talk is cheap, show me the code">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一缕烟气">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          RabbitMQ Tutorials
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-12-22 17:42:42" itemprop="dateCreated datePublished" datetime="2021-12-22T17:42:42+08:00">2021-12-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-02-18 10:52:04" itemprop="dateModified" datetime="2022-02-18T10:52:04+08:00">2022-02-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Framework/" itemprop="url" rel="index"><span itemprop="name">Framework</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>9.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>8 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><div style="color:Chocolate;text-align:center;display:inline-block;width:100%;">
闲时与你立黄昏，笑问灶前粥可温。
</div><br><span id="more"></span></p>
<p><a target="_blank" rel="noopener" href="https://www.rabbitmq.com/getstarted.html">参考文档</a></p>
<h1 id="使用-RabbitMQ-创建消息的几种方式"><a href="#使用-RabbitMQ-创建消息的几种方式" class="headerlink" title="使用 RabbitMQ 创建消息的几种方式"></a>使用 RabbitMQ 创建消息的几种方式</h1><ol>
<li>Hello World</li>
<li>Work queues</li>
<li>Publish/Subscribe</li>
<li>Routing</li>
<li>Topics</li>
<li>RPC</li>
<li>Publisher Confirms</li>
</ol>
<h1 id="Hello-World"><a href="#Hello-World" class="headerlink" title="Hello World"></a>Hello World</h1><h2 id="RabbitMQ-的定义"><a href="#RabbitMQ-的定义" class="headerlink" title="RabbitMQ 的定义"></a>RabbitMQ 的定义</h2><p>   RabbitMQ 是一个消息中间人，它接收和发送消息。<br>   你可以认为它是一个邮局: 当你在邮箱里放一个你想发送的信件，你可以确认信件最终会发送到接收者手中。<br>   打个比方，RabbitMQ 就像一个邮箱、一个邮局和一个信件收纳人。<br>   RabbitMQ 和邮局之间最大的不同就是它不和纸张打交道, 代替的，它接收、存储、发送二进制的数据信息。</p>
<h2 id="RabbitMQ-和一般消息传递，常用的一些行话"><a href="#RabbitMQ-和一般消息传递，常用的一些行话" class="headerlink" title="RabbitMQ 和一般消息传递，常用的一些行话"></a>RabbitMQ 和一般消息传递，常用的一些行话</h2><ul>
<li>Producing :: 它无非就是发送的意思。</li>
<li>Producer :: 一个发送信息的程序</li>
<li>queue :: RabbitMQ 中的邮箱<br>尽管消息流经 RabbitMQ 和你的程序，但是它们存储在队列中。<br>队列只受主机的内存和磁盘的影响，它本质上是一个大的缓存区。</li>
<li>Consuming :: 和接收是类似的意思。</li>
<li>consumer :: 主要用来接收信息的程序</li>
</ul>
<h2 id="使用-Java-客户端"><a href="#使用-Java-客户端" class="headerlink" title="使用 Java 客户端"></a>使用 Java 客户端</h2><p>在 java 中写两个程序，一个是发送单个信息的生产者，一个是接收信息并打印它们的消费者。</p>
<h2 id="Sending"><a href="#Sending" class="headerlink" title="Sending"></a>Sending</h2><p>我们将调用我们的消息发送者 <em>Send</em> 和消息消费者 <strong>Recv</strong>.<br>消费者将会连接到 RabbitMQ, 发送一条消息，然后退出。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">package</span> personal.wd.helloworld;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> dong2.wang</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2021/12/23 14:04</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Send</span> {</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">"hello"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception {</span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        connectionFactory.setHost(<span class="string">"47.100.236.167"</span>);</span><br><span class="line">        connectionFactory.setUsername(<span class="string">"admin"</span>);</span><br><span class="line">        connectionFactory.setPassword(<span class="string">"admin"</span>);</span><br><span class="line">        <span class="keyword">try</span> (<span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> connectionFactory.newConnection();</span><br><span class="line">             <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel()</span><br><span class="line">        ) {</span><br><span class="line">            channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">"Hello World"</span>;</span><br><span class="line">            channel.basicPublish(<span class="string">""</span>, QUEUE_NAME, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">" [x] Sent '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="Receiving"><a href="#Receiving" class="headerlink" title="Receiving"></a>Receiving</h2><p>我们的消费者会监听来自发送者的信息，因此不像只发送一次消息的发送者，我们要保持消费者一直运行以监听消息并把它们打印出来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">package</span> personal.wd.helloworld;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> dong2.wang</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2021/12/23 14:41</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Recv</span> {</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">"hello"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception {</span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        connectionFactory.setHost(<span class="string">"47.100.236.167"</span>);</span><br><span class="line">        connectionFactory.setUsername(<span class="string">"admin"</span>);</span><br><span class="line">        connectionFactory.setPassword(<span class="string">"admin"</span>);</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> connectionFactory.newConnection();</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 回调函数</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="literal">true</span>, (consumerTag, delivery) -&gt; {</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(delivery.getBody(), StandardCharsets.UTF_8);</span><br><span class="line">            System.out.println(<span class="string">" [x] Received: '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        }, consumerTag -&gt; {</span><br><span class="line">        });</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="Listing-queues"><a href="#Listing-queues" class="headerlink" title="Listing queues"></a>Listing queues</h2><p>你想要看看 RabbitMQ 中的多少的队列，和队列中有多少的信息。你可以使用 <strong>rabbitmqctl</strong> 工具来查看。</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo rabbitmqctl list_queues</span><br></pre></td></tr></table></figure>
<p>在 Windows 电脑的话，忽略掉 sudo<br><em>rabbitmqctl list_queues</em></p>
<h1 id="Wrok-queues-工作队列"><a href="#Wrok-queues-工作队列" class="headerlink" title="Wrok queues (工作队列)"></a>Wrok queues (工作队列)</h1><p>这个章节我们将创建一个工作队列，用于在多个工作人员之间分发耗时的任务。<br>这个概念在短的 http 请求窗口不能处理复杂任务的 web 程序中非常有用的。</p>
<h2 id="Massage-acknowlesgment-消息确认"><a href="#Massage-acknowlesgment-消息确认" class="headerlink" title="Massage acknowlesgment(消息确认)"></a>Massage acknowlesgment(消息确认)</h2><p>完成一个任务会花费几秒钟。你可以想知道一个消费者开始一项长期的任务并在只完成部分时死亡了会发生什么。<br><strong>现在我们的代码，RabbitMQ 一旦将消息传递给消费者，它会立即将其标记为删除。这样的话，当消费者程序出现异常或错误的时候，它正在处理的消息将会丢失。</strong></p>
<p>为了确保信息永远不会丢失，RabbitMQ 支持 <strong>message acknowledgment</strong>. 消费者会发回一个确认消息，告诉 RabbitMQ 特定消息已被接收、处理，并且 RabbitMQ 可以自由删除它。</p>
<p>默认 30 分钟的超时时间强制消费者去交付确认信息。</p>
<h2 id="Message-durability-消息持久化"><a href="#Message-durability-消息持久化" class="headerlink" title="Message durability(消息持久化)"></a>Message durability(消息持久化)</h2><p>我们已经学会如何确保当消费者程序异常的时候，消息不会丢失。<strong>但是如果RabbitMQ 的服务器停止的话，我们的消息依然会丢失。</strong><br>我们需要做两件事来确保消息不会丢失:</p>
<ol>
<li>将队列标记为永久的</li>
<li>将消息标记为永久的</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 队列持久化</span></span><br><span class="line"><span class="type">boolean</span> <span class="variable">durable</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">channel.queueDeclare(QUEUE_NAME, durable, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"><span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> String.join(<span class="string">" "</span>, args);</span><br><span class="line"><span class="comment">// 消息持久化</span></span><br><span class="line">channel.basicPublish(<span class="string">""</span>, QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());</span><br><span class="line">System.out.println(<span class="string">" [x] Sent '"</span> + message + <span class="string">"'"</span>);</span><br></pre></td></tr></table></figure>
<h2 id="Fair-dispatch-公平分派"><a href="#Fair-dispatch-公平分派" class="headerlink" title="Fair dispatch(公平分派)"></a>Fair dispatch(公平分派)</h2><p>你可能已经注意到任务分配仍然不能按照我们想要的来分配。<br>比如一个情形，有两个消费者，当所有偶数的消息会非常繁忙，所有的奇数的消息会非常清闲，那么一个消费者会很忙，而另一个几乎没有事情可以做。<br>为了解决这个问题，可以做如下的修改:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="variable">prefetchCount</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">channel.basicQos(prefetchCount);</span><br></pre></td></tr></table></figure></p>
<h1 id="Publish-Subscribe"><a href="#Publish-Subscribe" class="headerlink" title="Publish/Subscribe"></a>Publish/Subscribe</h1><p>这个章节我们将发送一个消息到多个消费者。这个模式被称为 “发布/订阅”.<br>本质上，发布日志信息将会广播给所有的消费者。</p>
<h2 id="Exchanges"><a href="#Exchanges" class="headerlink" title="Exchanges"></a>Exchanges</h2><p>在之前我们都是通过队列来发送和接收消息的。现在我们引入下 rabbit 中的完整的消息模型。<br>RabbitMQ 消息传递模型的核心思想是生产者从不直接向队列发送任何消息。<br>相反，生产者只能发送信息到 exchange.<br><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/001.png" alt="发送消息的模式"></p>
<p>下面有一些交换的类型:</p>
<ul>
<li>direct</li>
<li>topic</li>
<li>headers</li>
<li>fanout</li>
</ul>
<p>现在我们专注于最后一个: <strong>fanout</strong>。我们创建一个这个类型的交换机，叫做 <code>logs</code><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">channel.exchangeDeclare(<span class="string">"logs"</span>, <span class="string">"fanout"</span>);</span><br></pre></td></tr></table></figure><br>我们可以发送到我们命名的交换机:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">channel.basicPublish(<span class="string">"logs"</span>, <span class="string">""</span>, <span class="literal">null</span>, message.getBytes());</span><br></pre></td></tr></table></figure></p>
<h2 id="Temporary-queues"><a href="#Temporary-queues" class="headerlink" title="Temporary queues"></a>Temporary queues</h2><p>声明一个临时的队列:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> channel.queueDeclare().getQueue();</span><br></pre></td></tr></table></figure></p>
<h2 id="Binding"><a href="#Binding" class="headerlink" title="Binding"></a>Binding</h2><p>现在我们已经创建扇形的交换机和队列。我们要告诉交换机发送信息到我们的队列。交换机和队列之间的关系叫做绑定。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">channel.queueBind(queueName, <span class="string">"logs"</span>, <span class="string">""</span>);</span><br></pre></td></tr></table></figure><br>使用命令行查看绑定关系和队列<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo rabbitmqctl list_bindings</span><br></pre></td></tr></table></figure><br>查询结果如下:<br><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/002.png" alt="查询结果"></p>
<h1 id="Routing"><a href="#Routing" class="headerlink" title="Routing"></a>Routing</h1><p>上面我们已经能够广播日志信息到多个消费者。<br>现在我们可以添加一个特性—只广播日志消息的一个子集。</p>
<h2 id="Binding-1"><a href="#Binding-1" class="headerlink" title="Binding"></a>Binding</h2><p>以前绑定交换机和队列之间的关系是像下面这样绑定的:<br><code>channel.queueBind(queueName, EXCHANGE_NAME, "");</code><br>绑定时可以添加一个额外的参数 <code>routingKey</code>.为了避免冲突，我们把这个 <code>routingKey</code> 叫做 <code>binding_key</code>.<br>现在我们可以像下面一样创建绑定:<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">"black"</span>);</span><br></pre></td></tr></table></figure><br>binding_key 的含义取决于 exchange 的类型。</p>
<h2 id="Direct-Exchange"><a href="#Direct-Exchange" class="headerlink" title="Direct Exchange"></a>Direct Exchange</h2><p>Direct Exchange 可以向消费者发送指定类型的信息。<br>binding_key 和 routing_key 严格匹配的时候，Exchange 才会将消息发送到该队列中。<br>如下图所示：<br><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/003.png" alt></p>
<h2 id="Multiple-bindings"><a href="#Multiple-bindings" class="headerlink" title="Multiple bindings"></a>Multiple bindings</h2><p>给多个队列绑定相同的 key 是完全合法的。如果这样使用的话，Direct Exchange 就和 Fanout Exchange 是一样的，会将所有的信息广播给所有的消费者。<br><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/004.png" alt></p>
<h2 id="Emitting-Logs"><a href="#Emitting-Logs" class="headerlink" title="Emitting Logs"></a>Emitting Logs</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个 exchange</span></span><br><span class="line">channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"direct"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送一条消息</span></span><br><span class="line">channel.basicPublish(EXCHANGE_NAME, severity, <span class="literal">null</span>, message.getBytes());</span><br></pre></td></tr></table></figure>
<h2 id="发送者和消费者的参考类"><a href="#发送者和消费者的参考类" class="headerlink" title="发送者和消费者的参考类"></a>发送者和消费者的参考类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> personal.wd.helloworld;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> dong2.wang</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2021/12/23 14:04</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">EmitLogsDirect</span> {</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">"direct_logs"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception {</span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        connectionFactory.setHost(<span class="string">"47.100.236.167"</span>);</span><br><span class="line">        connectionFactory.setUsername(<span class="string">"admin"</span>);</span><br><span class="line">        connectionFactory.setPassword(<span class="string">"admin"</span>);</span><br><span class="line">        <span class="keyword">try</span> (<span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> connectionFactory.newConnection();</span><br><span class="line">             <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel()</span><br><span class="line">        ) {</span><br><span class="line">            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);</span><br><span class="line">            <span class="type">String</span> <span class="variable">severity</span> <span class="operator">=</span> getSeverity(args);</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> getMessage(args);</span><br><span class="line">            channel.basicPublish(EXCHANGE_NAME, severity, <span class="literal">null</span>, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line">            System.out.println(<span class="string">" [x] Sent '"</span> + severity + <span class="string">"':'"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getSeverity</span><span class="params">(String[] args)</span> {</span><br><span class="line">        <span class="keyword">return</span> args[<span class="number">0</span>];</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getMessage</span><span class="params">(String[] args)</span> {</span><br><span class="line">        <span class="keyword">return</span> args[<span class="number">1</span>];</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> personal.wd.helloworld;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> dong2.wang</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2021/12/23 14:41</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ReceiveLogsDirect</span> {</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">"direct_logs"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception {</span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        connectionFactory.setHost(<span class="string">"47.100.236.167"</span>);</span><br><span class="line">        connectionFactory.setUsername(<span class="string">"admin"</span>);</span><br><span class="line">        connectionFactory.setPassword(<span class="string">"admin"</span>);</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> connectionFactory.newConnection();</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明一个 direct 类型的 exchange</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);</span><br><span class="line">        <span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 进行多重绑定</span></span><br><span class="line">        <span class="keyword">for</span> (String severity : args) {</span><br><span class="line">            channel.queueBind(queueName, EXCHANGE_NAME, severity);</span><br><span class="line">        }</span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 回调函数</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="literal">true</span>, (consumerTag, delivery) -&gt; {</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(delivery.getBody(), StandardCharsets.UTF_8);</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + delivery.getEnvelope().getRoutingKey() + <span class="string">"':'"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        }, consumerTag -&gt; {</span><br><span class="line">        });</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h1 id="Topics"><a href="#Topics" class="headerlink" title="Topics"></a>Topics</h1><p>Direct Exchange 已经可以根据特定的 RoutingKey 来发送数据。但是还是不够灵活。</p>
<h2 id="Topic-Exchange"><a href="#Topic-Exchange" class="headerlink" title="Topic Exchange"></a>Topic Exchange</h2><p>Topic Exchange 中的 RoutingKey 不能是随意的，它必须是一系列以逗号分隔的字符。<br>这是有两件重要的情况：</p>
<ol>
<li><code>*</code>(star) 可以代替一个单词。</li>
<li><code>#</code>(hash) 可以代替零个或多个单词。</li>
</ol>
<p><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/005.png" alt></p>
<h1 id="RPC"><a href="#RPC" class="headerlink" title="RPC"></a>RPC</h1><h2 id="Client-Interface"><a href="#Client-Interface" class="headerlink" title="Client Interface"></a>Client Interface</h2><h2 id="Callback-queue"><a href="#Callback-queue" class="headerlink" title="Callback queue"></a>Callback queue</h2><h2 id="Correlation-Id"><a href="#Correlation-Id" class="headerlink" title="Correlation Id"></a>Correlation Id</h2><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p><img src="http://localhost:4000/2021/12/22/RabbitMQ-Tutorials/006.png" alt></p>
<h1 id="Publisher-Confirms"><a href="#Publisher-Confirms" class="headerlink" title="Publisher Confirms"></a>Publisher Confirms</h1><h2 id="Enabling-Publisher-Confirms-On-a-Channer"><a href="#Enabling-Publisher-Confirms-On-a-Channer" class="headerlink" title="Enabling Publisher Confirms On a Channer"></a>Enabling Publisher Confirms On a Channer</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">channel.confirmSelect();</span><br></pre></td></tr></table></figure>
<h2 id="Strategy-1-Publishing-Messages-Individually"><a href="#Strategy-1-Publishing-Messages-Individually" class="headerlink" title="Strategy #1: Publishing Messages Individually"></a>Strategy #1: Publishing Messages Individually</h2><h2 id="Strategy-2-Publishing-Messages-in-Batches"><a href="#Strategy-2-Publishing-Messages-in-Batches" class="headerlink" title="Strategy #2: Publishing Messages in Batches"></a>Strategy #2: Publishing Messages in Batches</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="variable">batchSize</span> <span class="operator">=</span> <span class="number">100</span>;</span><br><span class="line"><span class="type">int</span> <span class="variable">outstandingMessageCount</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"><span class="keyword">while</span> (thereAreMessagesToPublish()) {</span><br><span class="line">    <span class="type">byte</span>[] body = ...;</span><br><span class="line">    <span class="type">BasicProperties</span> <span class="variable">properties</span> <span class="operator">=</span> ...;</span><br><span class="line">    channel.basicPublish(exchange, queue, properties, body);</span><br><span class="line">    outstandingMessageCount++;</span><br><span class="line">    <span class="keyword">if</span> (outstandingMessageCount == batchSize) {</span><br><span class="line">        ch.waitForConfirmsOrDie(<span class="number">5_000</span>);</span><br><span class="line">        outstandingMessageCount = <span class="number">0</span>;</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"><span class="keyword">if</span> (outstandingMessageCount &gt; <span class="number">0</span>) {</span><br><span class="line">    ch.waitForConfirmsOrDie(<span class="number">5_000</span>);</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="Strategy-3-Handing-Publisher-Confirms-Asynchronously"><a href="#Strategy-3-Handing-Publisher-Confirms-Asynchronously" class="headerlink" title="Strategy #3: Handing Publisher Confirms Asynchronously"></a>Strategy #3: Handing Publisher Confirms Asynchronously</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">channel.confirmSelect();</span><br><span class="line">channel.addConfirmListener((sequenceNumber, multiple) -&gt; {</span><br><span class="line">    <span class="comment">// code when message is confirmed</span></span><br><span class="line">}, (sequenceNumber, multiple) -&gt; {</span><br><span class="line">    <span class="comment">// code when message is nack-ed</span></span><br><span class="line">});</span><br></pre></td></tr></table></figure>
<p>这里有两个回调函数，一个用于消息确认，一个用于 nack-ed 消息(可以认为是代理丢弃的消息).</p>
<h2 id="Summary-1"><a href="#Summary-1" class="headerlink" title="Summary"></a>Summary</h2><ul>
<li>逐条发送信息，同步等待响应 :: 简单，但是非常限制吞吐量</li>
<li>批量发送消息，同步等待一个批次的响应 :: 简单，合理的吞吐量，但是当发生错误的时候很难去排查原因</li>
<li>异步处理 :: 最佳性能和资源使用，发生错误时的良好控制，但是想要正确地实现比较复杂</li>
</ul>
<hr>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/RabbitMQ/" rel="tag"># RabbitMQ</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/07/30/emacs%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E4%BD%BF%E7%94%A8/" rel="prev" title="emacs正则表达式的使用">
      <i class="fa fa-chevron-left"></i> emacs正则表达式的使用
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/12/27/vue-cookie%E4%BD%BF%E7%94%A8/" rel="next" title="vue-cookie使用">
      vue-cookie使用 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-RabbitMQ-%E5%88%9B%E5%BB%BA%E6%B6%88%E6%81%AF%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="nav-number">1.</span> <span class="nav-text">使用 RabbitMQ 创建消息的几种方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hello-World"><span class="nav-number">2.</span> <span class="nav-text">Hello World</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#RabbitMQ-%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="nav-number">2.1.</span> <span class="nav-text">RabbitMQ 的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RabbitMQ-%E5%92%8C%E4%B8%80%E8%88%AC%E6%B6%88%E6%81%AF%E4%BC%A0%E9%80%92%EF%BC%8C%E5%B8%B8%E7%94%A8%E7%9A%84%E4%B8%80%E4%BA%9B%E8%A1%8C%E8%AF%9D"><span class="nav-number">2.2.</span> <span class="nav-text">RabbitMQ 和一般消息传递，常用的一些行话</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Java-%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="nav-number">2.3.</span> <span class="nav-text">使用 Java 客户端</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Sending"><span class="nav-number">2.4.</span> <span class="nav-text">Sending</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Receiving"><span class="nav-number">2.5.</span> <span class="nav-text">Receiving</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Listing-queues"><span class="nav-number">2.6.</span> <span class="nav-text">Listing queues</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Wrok-queues-%E5%B7%A5%E4%BD%9C%E9%98%9F%E5%88%97"><span class="nav-number">3.</span> <span class="nav-text">Wrok queues (工作队列)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Massage-acknowlesgment-%E6%B6%88%E6%81%AF%E7%A1%AE%E8%AE%A4"><span class="nav-number">3.1.</span> <span class="nav-text">Massage acknowlesgment(消息确认)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Message-durability-%E6%B6%88%E6%81%AF%E6%8C%81%E4%B9%85%E5%8C%96"><span class="nav-number">3.2.</span> <span class="nav-text">Message durability(消息持久化)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Fair-dispatch-%E5%85%AC%E5%B9%B3%E5%88%86%E6%B4%BE"><span class="nav-number">3.3.</span> <span class="nav-text">Fair dispatch(公平分派)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Publish-Subscribe"><span class="nav-number">4.</span> <span class="nav-text">Publish&#x2F;Subscribe</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Exchanges"><span class="nav-number">4.1.</span> <span class="nav-text">Exchanges</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Temporary-queues"><span class="nav-number">4.2.</span> <span class="nav-text">Temporary queues</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Binding"><span class="nav-number">4.3.</span> <span class="nav-text">Binding</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Routing"><span class="nav-number">5.</span> <span class="nav-text">Routing</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Binding-1"><span class="nav-number">5.1.</span> <span class="nav-text">Binding</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Direct-Exchange"><span class="nav-number">5.2.</span> <span class="nav-text">Direct Exchange</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Multiple-bindings"><span class="nav-number">5.3.</span> <span class="nav-text">Multiple bindings</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Emitting-Logs"><span class="nav-number">5.4.</span> <span class="nav-text">Emitting Logs</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%91%E9%80%81%E8%80%85%E5%92%8C%E6%B6%88%E8%B4%B9%E8%80%85%E7%9A%84%E5%8F%82%E8%80%83%E7%B1%BB"><span class="nav-number">5.5.</span> <span class="nav-text">发送者和消费者的参考类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Topics"><span class="nav-number">6.</span> <span class="nav-text">Topics</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Topic-Exchange"><span class="nav-number">6.1.</span> <span class="nav-text">Topic Exchange</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#RPC"><span class="nav-number">7.</span> <span class="nav-text">RPC</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Client-Interface"><span class="nav-number">7.1.</span> <span class="nav-text">Client Interface</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Callback-queue"><span class="nav-number">7.2.</span> <span class="nav-text">Callback queue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Correlation-Id"><span class="nav-number">7.3.</span> <span class="nav-text">Correlation Id</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Summary"><span class="nav-number">7.4.</span> <span class="nav-text">Summary</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Publisher-Confirms"><span class="nav-number">8.</span> <span class="nav-text">Publisher Confirms</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Enabling-Publisher-Confirms-On-a-Channer"><span class="nav-number">8.1.</span> <span class="nav-text">Enabling Publisher Confirms On a Channer</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Strategy-1-Publishing-Messages-Individually"><span class="nav-number">8.2.</span> <span class="nav-text">Strategy #1: Publishing Messages Individually</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Strategy-2-Publishing-Messages-in-Batches"><span class="nav-number">8.3.</span> <span class="nav-text">Strategy #2: Publishing Messages in Batches</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Strategy-3-Handing-Publisher-Confirms-Asynchronously"><span class="nav-number">8.4.</span> <span class="nav-text">Strategy #3: Handing Publisher Confirms Asynchronously</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Summary-1"><span class="nav-number">8.5.</span> <span class="nav-text">Summary</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">田园隐士</p>
  <div class="site-description" itemprop="description">talk is cheap, show me the code</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">347</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">53</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">田园隐士</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">587k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">8:53</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
          load: ['[tex]/mhchem'],
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
          packages: {'[+]': ['mhchem']},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  

</body>
</html>
